/* 
 * File:   winsocket.cpp
 * Author: robbiediaz
 * 
 * Created on January 27, 2009, 12:40 PM
 */

#ifdef WIN32

#include <string>

#include "winsocket.h"

winSocket::winSocket() {
    port = 5222;

    WSADATA WsaDat;
    if (WSAStartup(MAKEWORD(2, 0), &WsaDat) != 0) {
        WSACleanup();
    }

    socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (Socket == INVALID_SOCKET) {
        WSACleanup();
    }

    SOCKADDR_IN serverInf;
    serverInf.sin_family = AF_INET;
    serverInf.sin_addr.s_addr = INADDR_ANY;
    serverInf.sin_port = htons(port);

    if (bind(Socket, (SOCKADDR *) (&serverInf), sizeof (serverInf)) == SOCKET_ERROR) {
        WSACleanup();
    }
}

winSocket::~winSocket() {
    // Shutdown our socket
    shutdown(Socket, SD_SEND);

    // Close our socket entirely
    closesocket(Socket);

    // Cleanup Winsock
    WSACleanup();
}

void winSocket::sendString(std::string msg) {
    send(socket, msg.c_str(), msg.length(), 0);
}

std::string winSocket::readString() {
    std::string retMsg;
    char buffer[1000];
    while (recv(socket, buffer, 1000, 0) != 0)
        retMsg.append(buffer);

    return retMsg;
}

void winSocket::sockListen() {
    listen(socket, 1);

    SOCKET tempSock = SOCKET_ERROR;
    while (tempSock == SOCKET_ERROR) {
        tempSock = accept(socket, NULL, NULL);
    }
    socket = tempSock;
}

#endif
